package com.one.util;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class CheckCodeFromMysql {
    static final String url = "jdbc:mysql://localhost:3306/libsysdb";


    public static int  checkCode(String userName, String password) {

        Connection connection;
        Map<String, String> map = null;

        try {
            connection = DriverManager.getConnection(url, "root", "123456");
            //创建一个Statement对象来将sql语句发送到数据库
            PreparedStatement sql = connection.prepareStatement("select * from user_data where userName = ?");
            sql.setString(1, userName);
            ResultSet resultSet = sql.executeQuery();

            if (resultSet.next()) {
                map = new HashMap<>();
                map.put("userName", resultSet.getString("userName"));
                map.put("password", resultSet.getString("password"));
            } else return -1;   //-1表示账号不存在
        } catch (SQLException e) {
            e.printStackTrace();
        }

//        Map<String, String> checkCode = new HashMap<>();
//        checkCode.put(userName, password);

        if (map.get("password").equals(password)) {
            return 1; // 1表示用户账号和密码匹配 登录成功
        } else {
            return 0; // 0表示用户账号和密码不匹配 登录失败
        }
    }

    public static boolean isUserNameExits (String newName) {
        Connection connection;
        Vector<String> myName = null;
        try {
            connection = DriverManager.getConnection(url, "root", "123456");
            PreparedStatement sql = connection.prepareStatement("select * from user_data where userName = ?");
            sql.setString(1, newName);
            ResultSet resultSet = sql.executeQuery();
            if (resultSet.next()) {
                return true;
            } else return false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isBookNumberExits (int bookNumber) {
        Connection connection;
        Vector<String> myName = null;
        try {
            connection = DriverManager.getConnection(url, "root", "123456");
            PreparedStatement sql = connection.prepareStatement("select * from books where bookId = ?");
            sql.setInt(1, bookNumber);
            ResultSet resultSet = sql.executeQuery();
            if (resultSet.next()) {
                return true;
            } else return false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getUrl() {
        return url;
    }
}
